const express = require('express')
const { Manga, Chapter, UserFavorite } = require('../models')
const { Op } = require('sequelize')
const router = express.Router()

// 获取漫画列表
router.get('/', async (req, res) => {
  try {
    const {
      page = 1,
      limit = 20,
      category,
      tag,
      search,
      sort = 'lastUpdate',
      order = 'DESC'
    } = req.query

    const offset = (page - 1) * limit
    const where = { isActive: true }

    // 搜索条件
    if (search) {
      where[Op.or] = [
        { title: { [Op.like]: `%${search}%` } },
        { author: { [Op.like]: `%${search}%` } }
      ]
    }

    // 分类筛选
    if (category) {
      where.categories = {
        [Op.contains]: [category]
      }
    }

    // 标签筛选
    if (tag) {
      where.tags = {
        [Op.contains]: [tag]
      }
    }

    const { count, rows } = await Manga.findAndCountAll({
      where,
      limit: parseInt(limit),
      offset,
      order: [[sort, order]],
      include: [{
        model: Chapter,
        as: 'chapters',
        limit: 1,
        order: [['chapterNumber', 'DESC']]
      }]
    })

    res.json({
      data: rows,
      pagination: {
        total: count,
        page: parseInt(page),
        limit: parseInt(limit),
        pages: Math.ceil(count / limit)
      }
    })
  } catch (error) {
    console.error('获取漫画列表错误:', error)
    res.status(500).json({ error: '服务器错误' })
  }
})

// 获取漫画详情
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params
    const manga = await Manga.findByPk(id, {
      include: [{
        model: Chapter,
        as: 'chapters',
        order: [['chapterNumber', 'ASC']]
      }]
    })

    if (!manga) {
      return res.status(404).json({ error: '漫画不存在' })
    }

    res.json({ data: manga })
  } catch (error) {
    console.error('获取漫画详情错误:', error)
    res.status(500).json({ error: '服务器错误' })
  }
})

// 获取热门漫画
router.get('/rankings/popular', async (req, res) => {
  try {
    const { limit = 10 } = req.query
    
    const mangas = await Manga.findAll({
      where: { isActive: true },
      order: [['views', 'DESC']],
      limit: parseInt(limit)
    })

    res.json({ data: mangas })
  } catch (error) {
    console.error('获取热门漫画错误:', error)
    res.status(500).json({ error: '服务器错误' })
  }
})

// 获取最新更新
router.get('/updates/latest', async (req, res) => {
  try {
    const { limit = 10 } = req.query
    
    const mangas = await Manga.findAll({
      where: { isActive: true },
      order: [['lastUpdate', 'DESC']],
      limit: parseInt(limit),
      include: [{
        model: Chapter,
        as: 'chapters',
        limit: 1,
        order: [['chapterNumber', 'DESC']]
      }]
    })

    res.json({ data: mangas })
  } catch (error) {
    console.error('获取最新更新错误:', error)
    res.status(500).json({ error: '服务器错误' })
  }
})

// 获取分类列表
router.get('/categories/list', async (req, res) => {
  try {
    const categories = await Manga.findAll({
      attributes: ['categories'],
      where: { isActive: true }
    })

    const allCategories = new Set()
    categories.forEach(manga => {
      if (manga.categories) {
        manga.categories.forEach(cat => allCategories.add(cat))
      }
    })

    res.json({ data: Array.from(allCategories) })
  } catch (error) {
    console.error('获取分类列表错误:', error)
    res.status(500).json({ error: '服务器错误' })
  }
})

// 获取章节详情
router.get('/:mangaId/chapters/:chapterId', async (req, res) => {
  try {
    const { mangaId, chapterId } = req.params
    
    const chapter = await Chapter.findOne({
      where: {
        id: chapterId,
        mangaId: mangaId
      },
      include: [{
        model: Manga,
        as: 'manga'
      }]
    })

    if (!chapter) {
      return res.status(404).json({ error: '章节不存在' })
    }

    res.json({ data: chapter })
  } catch (error) {
    console.error('获取章节详情错误:', error)
    res.status(500).json({ error: '服务器错误' })
  }
})

module.exports = router
